import { resolve, extname } from 'path'
import { readFile } from 'fs/promises'

// MIME类型映射
const MIME_TYPES: Record<string, string> = {
	'.html': 'text/html',
	'.js': 'text/javascript',
	'.css': 'text/css',
	'.json': 'application/json',
	'.png': 'image/png',
	'.jpg': 'image/jpeg',
	'.gif': 'image/gif',
	'.svg': 'image/svg+xml',
	'.ico': 'image/x-icon',
}

// 默认MIME类型
const DEFAULT_MIME = 'application/octet-stream'

/**
 * 启动静态文件服务器
 * @param port 端口号
 * @param staticDir 静态文件目录
 */
export function startStaticServer(port: number = 8080, staticDir: string = './src') {
	console.log(`启动静态文件服务器，端口: ${port}，目录: ${staticDir}`)

	return Bun.serve({
		port,
		async fetch(req) {
			const url = new URL(req.url)
			let path = url.pathname

			// 处理根路径请求
			if (path === '/' || path === '') {
				path = '/frontend-example.html'
			}

			// 构建文件路径
			const filePath = resolve(process.cwd(), staticDir, path.slice(1))
			
			try {
				// 读取文件
				const file = Bun.file(filePath)
				const exists = await file.exists()
				
				if (!exists) {
					return new Response('文件未找到', { status: 404 })
				}
				
				// 获取MIME类型
				const ext = extname(filePath)
				const contentType = MIME_TYPES[ext] || DEFAULT_MIME
				
				// 返回文件内容
				return new Response(file, {
					headers: { 'Content-Type': contentType }
				})
			} catch (error) {
				console.error(`处理请求 ${path} 失败:`, error)
				return new Response('服务器错误', { status: 500 })
			}
		},
	})
} 